﻿using NCaptcha;
using System;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace Web.Infrastructure.Mvc.MvcCaptcha
{
    public class CaptchaController : Controller
    {
        [NoCache]
        public ActionResult Index(string name, int width = 120, int height = 30)
        {
            Captcha captcha = new Captcha(new { width = width, height = height });

            MemoryStream stream = new MemoryStream();
            captcha.Image.Save(stream, ImageFormat.Jpeg);
            var bytes = stream.ToArray();
            string value = captcha.Key;
            string cookieValue = value.Hash();
            HttpCookie cookie = new HttpCookie(name, cookieValue);
            cookie.Expires = DateTime.Now.AddMinutes(5);
            Response.SetCookie(cookie);
            return File(bytes, @"image/jpeg");
        }
    }
}